import React, { useState, useEffect } from 'react';
import { 
  Box, 
  Typography, 
  Paper, 
  TextField, 
  Button, 
  Table, 
  TableBody, 
  TableCell, 
  TableContainer, 
  TableHead, 
  TableRow,
  IconButton,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Stack
} from '@mui/material';
import { Delete as DeleteIcon, Edit as EditIcon, ArrowBack as ArrowBackIcon } from '@mui/icons-material';
import { invoke } from '@tauri-apps/api/core';
import { useNavigate } from 'react-router-dom';

const SqlCasePage = () => {
  const navigate = useNavigate();
  const [users, setUsers] = useState([]);
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [editingId, setEditingId] = useState(null);
  const [openDialog, setOpenDialog] = useState(false);

  // 加载用户列表
  const loadUsers = async () => {
    try {
      const result = await invoke('get_users');
      setUsers(JSON.parse(result));
    } catch (error) {
      console.error('Error loading users:', error);
    }
  };

  // 添加用户
  const addUser = async () => {
    try {
      await invoke('add_user', { name, email });
      setName('');
      setEmail('');
      loadUsers();
    } catch (error) {
      console.error('Error adding user:', error);
    }
  };

  // 更新用户
  const updateUser = async () => {
    try {
      await invoke('update_user', { id: editingId, name, email });
      setName('');
      setEmail('');
      setEditingId(null);
      setOpenDialog(false);
      loadUsers();
    } catch (error) {
      console.error('Error updating user:', error);
    }
  };

  // 删除用户
  const deleteUser = async (id) => {
    try {
      await invoke('delete_user', { id });
      loadUsers();
    } catch (error) {
      console.error('Error deleting user:', error);
    }
  };

  // 编辑用户
  const editUser = (user) => {
    setName(user.name);
    setEmail(user.email);
    setEditingId(user.id);
    setOpenDialog(true);
  };

  useEffect(() => {
    loadUsers();
  }, []);

  return (
    <Box sx={{ p: 3 }}>
      <Stack direction="row" alignItems="center" spacing={2} sx={{ mb: 3 }}>
        <IconButton 
          onClick={() => navigate('/')}
          sx={{ color: 'text.primary' }}
        >
          <ArrowBackIcon />
        </IconButton>
        <Typography variant="h4" component="h1">
          SQL Plugin 案例
        </Typography>
      </Stack>
      
      <Paper sx={{ p: 3, mb: 3 }}>
        <Typography variant="h6" gutterBottom>
          添加新用户
        </Typography>
        <Box sx={{ display: 'flex', gap: 2, mb: 2 }}>
          <TextField
            label="姓名"
            value={name}
            onChange={(e) => setName(e.target.value)}
          />
          <TextField
            label="邮箱"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
          />
          <Button 
            variant="contained" 
            onClick={editingId ? updateUser : addUser}
          >
            {editingId ? '更新' : '添加'}
          </Button>
        </Box>
      </Paper>

      <TableContainer component={Paper}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>ID</TableCell>
              <TableCell>姓名</TableCell>
              <TableCell>邮箱</TableCell>
              <TableCell>操作</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {users.map((user) => (
              <TableRow key={user.id}>
                <TableCell>{user.id}</TableCell>
                <TableCell>{user.name}</TableCell>
                <TableCell>{user.email}</TableCell>
                <TableCell>
                  <IconButton onClick={() => editUser(user)}>
                    <EditIcon />
                  </IconButton>
                  <IconButton onClick={() => deleteUser(user.id)}>
                    <DeleteIcon />
                  </IconButton>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>

      <Dialog open={openDialog} onClose={() => setOpenDialog(false)}>
        <DialogTitle>编辑用户</DialogTitle>
        <DialogContent>
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, mt: 2 }}>
            <TextField
              label="姓名"
              value={name}
              onChange={(e) => setName(e.target.value)}
            />
            <TextField
              label="邮箱"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setOpenDialog(false)}>取消</Button>
          <Button onClick={updateUser}>保存</Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default SqlCasePage; 